package top.wangjiu.reactive.rpc.registration;

import top.wangjiu.reactive.rpc.model.ServiceAddress;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName LocalConfigServerAddrList
 * @Description TODO
 * @Author wangjiu
 * @Date 2021/7/15 12:26 下午
 */
public class LocalConfigServerAddrList implements ServerAddrList{

    private final List<ServiceAddress> addressList = new ArrayList<>();

    public void addService(Class service, int version, String host,int port){
        addService(service,version,InetSocketAddress.createUnresolved(host,port));
    }

    public void addService(Class service, int version, InetSocketAddress address){
        addService(new ServiceAddress(service,version,address));
    }

    public void addService(ServiceAddress serviceAddress){
        addressList.add(serviceAddress);
    }

    @Override
    public List<InetSocketAddress> getAddressList(String service, int version) {
        return addressList.stream().filter(s->s.getService().getName().equals(service)&&s.getVersion()==version).map(ServiceAddress::getAddress).collect(Collectors.toList());
    }

    @Override
    public boolean verify(String service, int version, InetSocketAddress address) {
        Class serviceClass = null;
        try {
            serviceClass = Class.forName(service);
        } catch (ClassNotFoundException e) {
            return false;
        }
        ServiceAddress serviceAddress = new ServiceAddress(serviceClass, version, address);
        return addressList.stream().anyMatch(serviceAddress::equals);
    }
}
